package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.aliyun.oss.AliyunOssTemplate;
import com.heima.common.util.LoginUserInfo;
import com.heima.common.util.UserInfoThreadLocal;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * (WmMaterial)表服务实现类
 *
 * @author dwxw
 * @since 2023-03-06 11:49:18
 */
@Service("wmMaterialService")
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private WmMaterialMapper wmMaterialMapper;

    @Resource
    private AliyunOssTemplate aliyunOssTemplate;

    @Override
    public WmMaterial uploadPicture(MultipartFile multipartFile) throws IOException {
        //1. 获取到当前登录用户id
        LoginUserInfo loginUserInfo = UserInfoThreadLocal.get();
        Long userId = loginUserInfo.getId();
        //2. 上传图片到阿里云OSS , 获取图片访问路径
        //2.1 生成唯一文件名
        String filename = multipartFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = uuid + suffix;
        //2.2 上传文件
        String url = aliyunOssTemplate.upload(filename, multipartFile.getInputStream());
        //3. 封装数据 , 保存数据到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(userId.intValue());
        wmMaterial.setUrl(url);
        wmMaterial.setType(1);
        wmMaterial.setIsCollection(0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUpdatedTime(new Date());

        wmMaterialMapper.insert(wmMaterial);

        return wmMaterial;
    }

    @Override
    public IPage<WmMaterial> queryList(WmMaterialDto dto) {
        //1. 封装查询参数
        LambdaQueryWrapper<WmMaterial> lambdaQuery = Wrappers.<WmMaterial>lambdaQuery();
        //1.1 是否收藏查询条件
        if (dto.getIsCollection().intValue() == 1) {
            lambdaQuery.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //1.2 当前登录用户条件
        lambdaQuery.eq(WmMaterial::getUserId, UserInfoThreadLocal.get().getId());
        //1.3 分页参数
        Page<WmMaterial> page = new Page<WmMaterial>(dto.getPage(), dto.getSize());
        //2. 执行查询
        wmMaterialMapper.selectPage(page, lambdaQuery);

        return page;
    }

}

